package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

// 把类交给容器管理
@Component
@Slf4j
public class OrderTask {
    // 注入订单的mapper层
    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void processTimeoutOrder() {
        log.info("开始处理超时订单：{}", LocalDateTime.now());
        // 当前时间是否已经超过下单时间15分钟
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        // 找状态为未支付，下单时间超过15分钟的订单
        List<Orders> ordersList = ordersMapper.getByStatusAndOrderTimeLT(Orders.UN_PAID, time);
        for (Orders orders : ordersList) {
            // 订单状态修改为取消
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("支付超时，自动取消");
            orders.setCancelTime(LocalDateTime.now());
            ordersMapper.updateOrder(orders);
        }
    }

    /**
     * 处理派送中的订单
     */
    @Scheduled(cron = "0 0/10 * * * ? ")
    public void processDeliveryOrder(){
        log.info("开始处理派送中的订单{}",LocalDateTime.now());
        // 判断当前时间一个小时前下单的订单
        LocalDateTime time = LocalDateTime.now().plusHours(-2);
        // 找状态为派送中的,两个小时前下单的订单
        List<Orders> ordersList = ordersMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        // 修改状态为已送达
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
            ordersMapper.updateOrder(orders);
        }
    }
}
